// Copyright (c) 2025, yuxinyong and contributors
// For license information, please see license.txt
function reset_primary_button_for_related_samples(frm) {
    if (!frm.doc.__islocal && frm.is_dirty()) {
        var unsaved = frm.doc.__unsaved || {};
        var onlyRelated = true;
        
        for (var key in unsaved) {
            if (key !== 'related_samples' && !key.startsWith('related_samples.')) {
                onlyRelated = false;
                break;
            }
        }
        
        if (onlyRelated) {
            frm.dirty(false);
            delete frm.doc.__unsaved;
            frm.toolbar.set_primary_action();
        }
    }
}
function change_sample_status(frm, status) {
    let method_name = status == "Closed" ? "close_sample" : "stop_unstop";
    frappe.call({
        method: `zelin_shoe_biz.shoe_biz.doctype.shoe_sample.shoe_sample.${method_name}`,
        freeze: true,
        freeze_message: __("Updating sample status"),
        args: {
            sample: frm.doc.name,
            status: status,
        },
        callback: function (r) {
            if (r.message) {
                frm.set_value("status", r.message);
                frm.reload_doc();
            }
        },
    });
}

function set_custom_buttons(frm) {
    var doc = frm.doc;

    if (doc.docstatus === 1 && doc.status !== "Closed") {
        frm.add_custom_button(
            __("Close"),
            function () {
                frappe.confirm(__("Once the Sample is Closed. It can't be resumed."), () => {
                    change_sample_status(frm, "Closed");
                });
            },
            __("Status")
        );
    }

    if (doc.docstatus === 1 && !["Closed", "Completed"].includes(doc.status)) {
        if (doc.status != "Stopped" && doc.status != "Completed") {
            frm.add_custom_button(
                __("Stop"),
                function () {
                    change_sample_status(frm, "Stopped");
                },
                __("Status")
            );
        } else if (doc.status == "Stopped") {
            frm.add_custom_button(
                __("Re-open"),
                function () {
                    change_sample_status(frm, "Resumed");
                },
                __("Status")
            );
        }
    }
}

frappe.ui.form.on("Shoe Sample", {
    before_save: function(frm) {
        if (frm.doc.related_samples && frm.doc.related_samples.length > 0) {
            frm.doc.related_samples = [];
        }
    },
    onload: function(frm) {
        reset_primary_button_for_related_samples(frm)
    },
    copy_field_to_quick_entry(frm){
	    let article_field = frm.get_docfield("shoe_parts", "article");
		article_field.get_route_options_for_new_doc = function(row) {		
            return {"item_group": "ARTICLE"}        
		}        
        let construction_field = frm.get_docfield("construction");
		construction_field.get_route_options_for_new_doc = function(row) {		
            return {
                "last": row.doc.last
            }        
		}
	    let style_variant_field = frm.get_docfield("style_variant");
		style_variant_field.get_route_options_for_new_doc = function(row) {		
            return {
                "style": row.doc.style,
                "shoe_material": row.doc.shoe_material
            }        
		}                  
    },
    setup(frm) {
        frm.trigger("copy_field_to_quick_entry");
    },    
	refresh(frm) {
        reset_primary_button_for_related_samples(frm);

        set_custom_buttons(frm)
        
        frm.set_query("article", "shoe_parts", function (doc, cdt, cdn) {
			const row = locals[cdt][cdn];
			return {
				query: "zelin_shoe_biz.queries.get_article",
				filters: {
					shoe_part: row.shoe_part,                    
				},
			};
		});        
        frm.set_query("item_code", "shoe_parts", function(doc, cdt, cdn) {
			const row = locals[cdt][cdn];
            let filters = {shoe_part: row.shoe_part}
            if (row.article){
                filters.article = row.article
            }
			return {
				query: "zelin_shoe_biz.queries.get_item_code",
				filters: filters
			};
        })

		if (frm.doc.docstatus === 1 && frm.doc.shoe_material && frm.doc.sample_stage === "Confirm" &&
            frm.doc.locked === 1 && !frm.doc.item_code
        ){
			frm.add_custom_button(__('Create Item'), () => {
				frm.call('create_items')
				.then( (r) =>{
					if (r.message){
						frappe.show_alert(__("Items Created"))
						frm.refresh();	//隐藏当前菜单按钮
						frm.reload_doc();
					}
				})
			});
		}
	}
});
